var api = require('../../utils/api.js')
var app = getApp();
var util = require('../../utils/util.js');

var currentShopId = 0;
var currentTime = app.globalData.global_current_time;
var currentType = 0;
var currentPage = 1;
var saleDetailLists = [];
var currentMachineId = 0;
var storeArr = [];
var machineArr = [];
//排序
var detail_sort_field = 0; //0：sales_money 1：sales_num（排序字段）
var detail_sort_type = 0; //0：降序 1：升序
var shop_sort_field = 1;//1销售额 2销售量
var shop_sort_type = 1;//1降序 2升序
var currentSaleDetail = [];//用于判断是否停止上拉加载
var isOnShow = true;//用于判断是否为切换后的页面
var alreadyClickStoreMore = false;

Page({

  data: {
    times: ['累计', '昨日', '本周', '本月', '本年'],
    types: ['全部', '销售', '自提'],
    currentTab: 0,
    typesTab: 0,
    isSalesNumber: false,
    clickCount: 0,
    sales: [],
    shops: [],
    isStoreSalesNumber: false,
    storeClickCount: 0,
    actionSheetHidden: true,
    currentMachineName: '',
    showSaleDetail: false,
    // 1 表示选中向下 0:未选中 2:选中向上
    salesArrow_yuan: 1,
    salesArrow_number: 0,
    storeSalesArrow_yuan: 1,
    actionSheetHidden: true,
    storeSalesArrow_number: 0,
    screeningCol: true,
    endDate: "",
    startDate: "",
  },

  onLoad: function () {
    // this.autoLogin();
    var that = this;
    wx.getSystemInfo({
      success: function (res) {
        that.setData({
          HEIGHT: res.windowWidth,
        });
      }

    });

    that.setData({
      isYanJiu: app.globalData.is_server_Yan
    })
  },

  onShow: function () {
    //页面切换时，获取保存的数据
    alreadyClickStoreMore = false;
    isOnShow = true;
    currentTime = app.globalData.global_current_time;
    this.setData({
      currentTab: currentTime
    })

    var now = new Date();
    var year = now.getFullYear();
    var month = now.getMonth() + 1;
    var day = now.getDate();
    if (month < 10) {
      month = '0' + month;
    };
    if (day < 10) {
      day = '0' + day;
    };
    var formatDate = year + '-' + month + '-' + day;
    this.setData({
      endDate: formatDate,
      startDate: "请选择开始日期",
      ofEndDate: formatDate,
    })
    wx.setNavigationBarTitle({
      title: '销售统计',
    })
    this.autoLogin();

  },
  // 自动登录
  autoLogin: function () {
    var that = this;
    wx.login({
      success: function (res) {
        if (res.code) {
          var code = res.code;
          var params = new Object()
          params.code = code;
          api.POST({
            params: params,
            url: app.globalData.login_url,
            success: function (respone) {
              util.hiddenLoading();
              if (respone.data.code) {
                switch (respone.data.code) {
                  case '11906':
                    wx.redirectTo({
                      url: '../login/login',
                    });
                    break;
                  case '5802':
                    util.showError("密码错误");
                    break;
                  case '2499':
                    util.showError("该账号已经绑定过其他微信账号了");
                    break;
                }
              } else {
                app.globalData.loginState = 1;
                wx.setStorageSync("isLogin", "1");
                var accountInfo = respone.data.data.result;
                app.globalData.accountInfo = accountInfo;
                var isYan = (accountInfo.type == 4);
                app.globalData.is_server_Yan = isYan;
                that.setData({ isYanJiu: isYan });
                that.loadStoreListData();
              }
            }, fail: function () {
              util.hiddenLoading();
            }
          })
        }
      },
      fail: function () {
        util.showError("网络错误");
      }
    })
  },

  refreshData: function () {
    currentPage = 1;
    currentMachineId = 0;
    this.loadShopSaleStatisticsData();
    this.loadShopSaleListData();
    this.loadShopMachineData();
    this.loadShopSaleDetailData();
  },

  //门店列表shopli
  loadStoreListData: function () {
    var that = this;
    api.POST({
      url: app.globalData.shopList_url,
      success: function (res) {
        var tempStoreArr = res.data.data;
        var allArr = [{ short_name: '全部', id: '0' }];

        //如果只有一家门店，则不显示门店选择栏目
        if (tempStoreArr.length > 1) {
          //如果发现数据门店被删除了，则默认跳转到第一个门店
          if (tempStoreArr.length + 1 < storeArr.length) {
            app.globalData.current_shop_index = 0;
          }
          storeArr = allArr.concat(tempStoreArr);

          that.setData({
            list: storeArr
          });

          that.setData({
            currentStoreSelect: 0,
          })

          currentShopId = storeArr[app.globalData.current_shop_index].id;
        } else if (tempStoreArr.length == 1) {
          storeArr = tempStoreArr;
          currentShopId = tempStoreArr[0].id;
          that.setData({
            list: []
          });

        } else {
          storeArr = [];
          that.setData({
            list: []
          });

        }
        that.refreshData();
        that.currentStoreSelectedMethod(app.globalData.current_shop_index);
      },
      fail: function (res) { console.log('fail' + res); },
      complete: function (res) { util.hiddenLoading(); },
    });
  },

  // 售酒机累计
  loadShopSaleStatisticsData: function () {
    var that = this;
    var params = new Object()
    params.shop_id = currentShopId;

    params.time = currentTime;
    params.type = currentType;
    if (currentTime == 0) {
      params.start_time = that.data.startDate;
      params.end_time = that.data.endDate;
    }
    api.POST({
      url: app.globalData.shopSaleStatistics_url,
      params: params,
      success: function (res) {
        that.setData({
          saleSatistics: res.data.data,
        })
      },
    })
  },
  // 总明细
  loadShopSaleDetailData: function () {
    var that = this;
    var params = new Object()
    params.shop_id = currentShopId;
    params.machine_id = currentMachineId;
    params.page = currentPage;
    params.limit = 10;
    params.time = currentTime;
    params.type = currentType;
    params.sort_field = detail_sort_field; //0：sales_money 1：sales_num（排序字段）
    params.sort_type = detail_sort_type; //0：降序 1：升序
    if (currentTime == 0) {
      params.start_time = that.data.startDate;
      params.end_time = that.data.endDate;
    }
    console.log('收入参数', params);
    api.POST({
      url: app.globalData.shopSaleDetail_url,
      params: params,
      success: function (res) {
        util.hiddenLoading();
        if (currentPage == 1) {
          saleDetailLists = [];
        }
        saleDetailLists = saleDetailLists.concat(res.data.data.list);
        currentSaleDetail = res.data.data.list;
        if (saleDetailLists.length > 0) {
          that.setData({
            sales: saleDetailLists,
            // sales: hahah,
            showSaleDetail: true,
          })
        } else {
          that.setData({

            showSaleDetail: false
          })
        }
      },
      fail: function (res) {
        console.log('fail' + res);
        util.hiddenLoading();
      },
      complete: function (res) {
        util.hiddenLoading();
      },
    })
  },

  //售酒机列表
  loadShopMachineData: function () {

    var that = this;
    var params = new Object()
    params.shop_id = currentShopId;
    params.time = currentTime
    params.type = currentType;
    if (currentTime == 0) {
      params.start_time = that.data.startDate;
      params.end_time = that.data.endDate;
    }
    api.POST({
      url: app.globalData.shopMachineSS_url,
      params: params,
      success: function (res) {
        if (!currentShopId || currentShopId == 0) {
          return;
        }
        if (res.data.data.length > 3) {
          that.setData({
            showCheckMachineMore: true,
          })
        } else {
          that.setData({
            showCheckMachineMore: false,
          })
        }
        machineArr = res.data.data;
        that.setData({
          machines: machineArr,
        })
        that.currentStoreSelectedMethod(app.globalData.current_shop_index);
      },
    })
  },

  //门店排名列表
  loadShopSaleListData: function () {
    var that = this;
    var params = new Object()
    params.time = currentTime;

    params.sort_field = shop_sort_field; //1销售额 2销售量
    params.sort_type = shop_sort_type; // 1降序 2升序
    if (currentTime == 0 && that.data.startDate.indexOf("请") < 0) {
      params.start_time = that.data.startDate;
      params.end_time = that.data.endDate;
    }

    console.log(params);
    api.POST({
      url: app.globalData.shopSaleList_url,
      params: params,
      success: function (res) {
        if (res.data.data.length > 3 && alreadyClickStoreMore == false) {
          that.setData({
            showCheckShopMore: true,
          })
        } else {
          that.setData({
            showCheckShopMore: false,
          })
        }
        that.setData({
          shops: res.data.data
        })
      },
    })
  },

  storeSelectMethod: function (e) {
    //门店切换时要将售酒机id置0
    currentMachineId = 0;
    // wx.setNavigationBarTitle({
    //   title: e.currentTarget.dataset.viewText,
    // });

    this.currentStoreSelectedMethod(e.currentTarget.dataset.currentStore);
    currentShopId = e.currentTarget.dataset.currentStoreId;
    this.refreshData();
  },


  currentStoreSelectedMethod: function (index) {
    app.globalData.current_shop_index = index;
    this.setData({
      currentStoreSelect: index,
    });

    //如果是全部且店铺个数>1，显示门店排名，否则隐藏
    if (index == 0 && storeArr.length > 1) {//点击全部

      this.setData({
        currentMachineName: "",
        showMachineInfo: false,
      })
      if (storeArr.length > 1) {//一个以上的门店
        this.setData({
          showStoreRank: true,
        })

      } else {//一个门店
        this.setData({
          showStoreRank: false,

        })
      }
      this.setData({
        showMachineInfo: false,
      });
    } else {
      this.setData({
        showStoreRank: false,
      });

      if (machineArr.length > 1) {//没有售酒机，隐藏售酒机列表
        this.setData({
          showMachineInfo: true,
          currentMachineName: "全部售酒机",
        })
      } else if (machineArr.length == 1) {
        this.setData({
          showMachineInfo: true,
          currentMachineName: "",
        })
      } else {
        this.setData({
          showMachineInfo: false,
          currentMachineName: "",
        })
      }
    }

  },



  swichNav: function (e) {
    this.setData({
      currentTab: e.target.dataset.currentTime,
    });
    currentTime = e.target.dataset.currentTime;
    app.globalData.global_current_time = currentTime;

    this.refreshData();
  },
  swichTypeNav: function (e) {
    this.setData({
      typesTab: e.target.dataset.currentTime,
    });
    currentType = e.target.dataset.currentTime;
    // app.globalData.global_current_time = currentTime;

    this.refreshData();
  },
  //日期选择
  actionDayChoose: function (e) {
    this.setData({
      screeningCol: !this.data.screeningCol
    })
  },

  //   销售额
  salesVolumeAction: function (e) {
    detail_sort_field = 0;
    this.salesChangeAction(false);
  },
  //   销售数量
  salesNumberAction: function (e) {
    detail_sort_field = 1;
    this.salesChangeAction(true);

  },

  salesChangeAction: function (isSalesNumberFlag) {

    if (this.data.isSalesNumber != isSalesNumberFlag) {
      this.setData({
        salesArrow_yuan: isSalesNumberFlag ? 0 : 1,
        salesArrow_number: isSalesNumberFlag ? 1 : 0,
        clickCount: 0
      })
    }

    this.setData({
      isSalesNumber: isSalesNumberFlag,
      clickCount: this.data.clickCount + 1
    })


    if (this.data.clickCount >= 2) {
      this.setData({
        salesArrow_yuan: isSalesNumberFlag ? 0 : ((this.data.salesArrow_yuan > 1) ? 1 : this.data.salesArrow_yuan + 1),
        salesArrow_number: isSalesNumberFlag ? ((this.data.salesArrow_number > 1) ? 1 : this.data.salesArrow_number + 1) : 0,
      })
    }
    if (isSalesNumberFlag == false) {
      detail_sort_type = ((this.data.salesArrow_yuan > 1) ? 1 : 0)
    }
    else {
      detail_sort_type = ((this.data.salesArrow_number > 1) ? 1 : 0)
    }
    currentPage = 1;
    this.loadShopSaleDetailData();
  },
  // 门店版
  storeSalesVolumeAction: function (e) {
    shop_sort_field = 1;
    this.storeSalesChangeAction(false);

  },
  storeSalesNumberAction: function (e) {
    shop_sort_field = 2;
    this.storeSalesChangeAction(true);
  },
  storeSalesChangeAction: function (isStoreSalesNumberFlag) {

    if (this.data.isStoreSalesNumber != isStoreSalesNumberFlag) {
      this.setData({
        storeClickCount: 0,
        storeSalesArrow_yuan: isStoreSalesNumberFlag ? 0 : 1,
        storeSalesArrow_number: isStoreSalesNumberFlag ? 1 : 0,
      })
    }

    this.setData({
      isStoreSalesNumber: isStoreSalesNumberFlag,
      storeClickCount: this.data.storeClickCount + 1
    })

    if (this.data.storeClickCount >= 2) {
      this.setData({
        storeSalesArrow_yuan: isStoreSalesNumberFlag ? 0 : ((this.data.storeSalesArrow_yuan > 1) ? 1 : this.data.storeSalesArrow_yuan + 1),
        storeSalesArrow_number: isStoreSalesNumberFlag ? ((this.data.storeSalesArrow_number > 1) ? 1 : this.data.storeSalesArrow_number + 1) : 0,

      })
    }

    if (isStoreSalesNumberFlag == false) {
      shop_sort_type = ((this.data.storeSalesArrow_yuan > 1) ? 2 : 1)
    }
    else {
      shop_sort_type = ((this.data.storeSalesArrow_number > 1) ? 2 : 1)
    }



    this.loadShopSaleListData();
  },

  // 查看更多
  checkMoreShopClicked: function () {
    alreadyClickStoreMore = true;
    this.setData({
      showCheckShopMore: false,
    })
  },
  checkMoreMachineClicked: function () {
    this.setData({
      showCheckMachineMore: false,
    })
  },

  onReachBottom: function () {
    if (currentSaleDetail.length < 10) {
      return;
    }
    currentPage = currentPage + 1;

    this.loadShopSaleDetailData();
    util.hiddenLoading();
  },

  onPullDownRefresh: function () {
    currentPage = 1;
    currentMachineId = 0;
    wx.showNavigationBarLoading('加载中');
    this.loadStoreListData();
    wx.hideNavigationBarLoading(); //完成停止加载
    wx.stopPullDownRefresh();
  },

  actionSheetTap: function (e) {
    if (machineArr.length <= 1 || this.data.currentMachineName == '') {//只有一家个售酒机或者点击全部时
      return;
    }
    var machineSelectArr = [{ machine_id: '0', name: '全部售酒机' }];
    machineSelectArr = machineSelectArr.concat(machineArr);
    var actionItems = [];
    for (var i = 0; i < machineSelectArr.length; i++) {

      var item = machineSelectArr[i];
      actionItems.push(item.name);
    }
    var that = this;
    if (actionItems.length > 6) {
      that.setData({

        actionSheetItems: actionItems,
        actionSheetHidden: false,
      })
    } else {
      wx.showActionSheet({
        itemList: actionItems,
        success(res) {
          if (res.cancel == true) {
            return;
          }
          currentPage = 1;
          currentMachineId = machineSelectArr[res.tapIndex].machine_id;
          that.loadShopSaleDetailData();
          that.setData({
            currentMachineName: machineSelectArr[res.tapIndex].name,
          })
        }
      })
    }

  },
  //若超过六个，则用这个组件
  listenerActionSheet: function () {

    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },

  bindActionTap: function (e) {
    var machineSelectArr = [{ machine_id: '0', name: '全部售酒机' }];
    machineSelectArr = machineSelectArr.concat(machineArr);
    currentPage = 1;
    currentMachineId = machineSelectArr[e.currentTarget.dataset.aindex].machine_id;
    this.setData({
      currentMachineName: machineSelectArr[e.currentTarget.dataset.aindex].name,
    })
    this.loadShopSaleDetailData();
    this.setData({
      actionSheetHidden: !this.data.actionSheetHidden
    })
  },
  actionCancelTap: function () {
    this.setData({
      actionSheetHidden: true
    })
  },

  startDateChange: function (e) {
    var time = e.detail.value
    this.setData({
      startDate: time
    })
  },
  endDateChange: function (e) {
    // console.log(e);
    var time = e.detail.value
    this.setData({
      endDate: time
    })
  },
  //时间筛选
  confirm: function () {
    var a = /^(\d{4})-(\d{2})-(\d{2})$/
    if (a.test(this.data.startDate)) {
      var start_time = this.data.startDate;
    }

    if (a.test(this.data.endDate)) {
      var end_time = this.data.endDate;
    }
    this.setData({
      currentPage: 1,
      start_time: start_time,
      end_time: end_time,
      screeningCol: true
    })
    this.refreshData();
  },
  cancel: function () {
    this.setData({
      screeningCol: true
    })
  },
}) 